﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using D = System.Drawing;
using Microsoft.Practices.Prism.Regions;
using TimeSplicerModule.DomainModels;
using TimeSplicerModule.ViewModels;
using TimeSplicerModule.Factories;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using TimeSplicerModule.Controllers;
using TimeSplicerModule.Services;
using Infrastucture;
using Infrastucture.Collections;

namespace TimeSplicerModule.Views
{
    /// <summary>
    /// Interaction logic for ProjectView.xaml
    /// </summary>
    public partial class ProjectView : UserControl, INavigationAware
    {
        private ProjectViewModel Model;
        private readonly IUnityContainer _container;
        private readonly IProjectController _projectController;
        private readonly ITaskController _taskController;
        private readonly IProjectService _projectService;
        private readonly IReportsService _reportsService;

        public ProjectView(IUnityContainer container, IProjectController projectController, ITaskController taskController, IProjectService projectService, IReportsService reportsService)
        {
            InitializeComponent();

            _container = container;
            _projectController = projectController;
            _taskController = taskController;
            _projectService = projectService;
            _reportsService = reportsService;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false; //throw new NotImplementedException();
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // throw new NotImplementedException();
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            this.progressBorder.Visibility = System.Windows.Visibility.Visible;
            this.progressRing.IsActive = true;

            if (navigationContext.Parameters.Count() == 0)
            {
                // will have to do brush color after the fact
                await Task.Run(() => Model = _projectService.CreateNew());

                D.Color c = D.Color.FromName(Model.Status.StatusColor);
                Color co = Color.FromArgb(c.A, c.R, c.G, c.B);
                Model.StatusBrushColor = new SolidColorBrush(co);
            }
            else
            {
                string id = navigationContext.Parameters["id"].ToString();
                Guid result;

                if (Guid.TryParse(id, out result))
                {
                    await Task.Run(() => Model = _projectService.GetViewModel(result));

                    D.Color c = D.Color.FromName(Model.Status.StatusColor);
                    Color co = Color.FromArgb(c.A, c.R, c.G, c.B);
                    Model.StatusBrushColor = new SolidColorBrush(co);
                }
            }

            if (Model.Tasks != null)
            {
                foreach (var t in Model.Tasks)
                {
                    t.Status.BrushColor = t.Status.SetBrushColor();
                }
            }


            this.progressBorder.Visibility = System.Windows.Visibility.Hidden;
            this.progressRing.IsActive = false;

            this.DataContext = Model;
        }

        private async void saveButton_Click(object sender, RoutedEventArgs e)
        {
            this.saveButton.IsEnabled = false;
            this.saveExitButton.IsEnabled = false;
            this.cancelButton.IsEnabled = false;
            this.addTask.IsEnabled = false;
           

            await Task.Run(() => Model = _projectService.Save(Model));


            this.saveButton.IsEnabled = true;
            this.saveExitButton.IsEnabled = true;
            this.cancelButton.IsEnabled = true;
            this.addTask.IsEnabled = true;
        }

        private async void saveExitButton_Click(object sender, RoutedEventArgs e)
        {
            await Task.Run(() => _projectService.Save(Model));
            cancelButton_Click(sender, e);
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            _projectController.NavigateToListView();
        }

        private void addTask_Click(object sender, RoutedEventArgs e)
        {
            _taskController.NavigateToItemView(Model.ProjectGuid, true);
        }

        private async void addUserButton_Click(object sender, RoutedEventArgs e)
        {
           if (this.usersComboBox.SelectedItem != null && this.projectRolesComboBox.SelectedItem != null)
           {
               var user = this.usersComboBox.SelectedItem as UserModel;
               var role = this.projectRolesComboBox.SelectedItem as ProjectRoleModel;

               await Task.Run(() => Model = _projectService.AddUser(Model, user, role));
           }
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListView list = sender as ListView;

            if (list.SelectedItem != null)
            {
                TaskModel task = list.SelectedItem as TaskModel;
                _taskController.NavigateToItemView(task.TaskGuid, false);
            }
        }

        private void projectUsersGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // need to add user to drop down so that they can have thier role changed
            if (this.projectUsersGrid.SelectedItem != null)
            {
                var projectUser = this.projectUsersGrid.SelectedItem as ProjectUserModel;
                setUser(projectUser.UserGuid);
                setRole(projectUser.ProjectRoleGuid);
            }
        }

        private void setUser(Guid userGuid)
        {
            this.usersComboBox.SelectedValue = userGuid;
        }
        private void setRole(Guid roleGuid)
        {
            this.projectRolesComboBox.SelectedValue = roleGuid;
        }

        private void users1ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            filterTasks();
        }

        private void taskStatusesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            filterTasks();
        }

        private void textSearchTextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            filterTasks();
        }

        private void filterTasks()
        {
            Model.SearchText = this.textSearchTextBox.Text;
            var user = (this.users1ComboBox.SelectedItem as ProjectUserModel).User;
            var status = this.taskStatusesComboBox.SelectedItem as StatusModel;

            if (String.IsNullOrEmpty(Model.SearchText))
            {
                if (status == null)
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && (x.Status.Status == Infrastucture.Status.In_Progress
                        || x.Status.Status == Infrastucture.Status.Suspended)).ToObservableCollection();
                else
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && x.StatusGuid == status.StatusGuid).ToObservableCollection();
            }
            else
            {
                if (status == null)
                {
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && (x.Status.Status == Infrastucture.Status.In_Progress
                        || x.Status.Status == Infrastucture.Status.Suspended)
                        && (x.Project.Name.ToLower().Contains(Model.SearchText.ToLower())
                        || x.Name.ToLower().Contains(Model.SearchText.ToLower()))).ToObservableCollection();
                }
                else
                {
                    Model.FilteredTasks = Model.Tasks.Where(x => x.AssignedToGuid == user.UserGuid
                        && x.StatusGuid == status.StatusGuid
                        && (x.Project.Name.ToLower().Contains(Model.SearchText)
                        || x.Name.ToLower().Contains(Model.SearchText))).ToObservableCollection();
                }
            }
        }

        private async void completeProjectButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO:
            MessageBoxResult result = MessageBox.Show("Are you sure you want to Complete this project?", "", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                this.saveButton.IsEnabled = false;
                this.saveExitButton.IsEnabled = false;
                this.cancelButton.IsEnabled = false;
                this.completeProjectButton.IsEnabled = false;
                this.addTask.IsEnabled = false;

                await Task.Run(() => Model = _projectService.Complete(Model));

                D.Color c = D.Color.FromName(Model.Status.StatusColor);
                Color co = Color.FromArgb(c.A, c.R, c.G, c.B);
                Model.StatusBrushColor = new SolidColorBrush(co);

                this.cancelButton.IsEnabled = true;

                this.DataContext = Model;
            }
        }

        private async void fullReportButton_Click(object sender, RoutedEventArgs e)
        {
            this.fullReportButton.IsEnabled = false;

            await Task.Run(() => _reportsService.FullProjectReport(Model.ProjectGuid));

            this.fullReportButton.IsEnabled = true;
        }
    }
}
